package service.impl;

import bean.Goods;
import bean.Sale;
import dao.GoodsDao;
import dao.SaleDao;
import exception.NotEnoughException;
import service.BuyGoodsService;

/**
 * @author HLF
 * @version V1.0
 * @package service.impl
 * @date 2021/10/21 20:04
 *
 * 这样没有事务时，销售记录增加了，但是库存不足时或者商品找不到时销售记录却增加了
 * 应该增加事务功能，使用事务的回滚
 * 如果增加了事务，二者共同成功或失败
 */
public class BuyGoodsServiceImpl implements BuyGoodsService {
    private GoodsDao goodsDao = null;
    private SaleDao saleDao = null;

    @Override
    public void buy(Integer goodsId, Integer nums) {
        System.out.println("buy方法开始");

        //1.记录销售信息，向sale表添加记录
        Sale sale = new Sale(null, goodsId, nums);
        saleDao.insertSale(sale);

        //2.更新库存
        Goods goods = goodsDao.selectGoods(goodsId);
        if (goods == null) {
            //商品不存在
            throw new NullPointerException("编号为" + goodsId + "的商品不存在！");
        } else if (nums > goods.getAmount()) {
            //商品库存不足
            throw new NotEnoughException("编号为" + goodsId + "的商品数量不足！");
        } else {
            //修改库存
            Goods buyGoods = new Goods();
            buyGoods.setId(goodsId);
            buyGoods.setAmount(nums);
            goodsDao.updateGoods(buyGoods);

            System.out.println("buy方法结束");
        }
    }


    //set设值注入给goodsDao赋值
    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    //set设值注入给saleDao赋值
    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }
}
